package com.lzx.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * @author 程序员星星
 * @date 2022/11/27
 * @Description
 */
public class ExcelUtils {
    public static void export(HttpServletResponse response, String fileName, Class<?> t, List<?> list) {
        try {
            ExportParams exportParams = new ExportParams(null, fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, t, list);
            //当前时间作为文件名
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
            String nowDate = sdf.format(calendar.getTime());
            fileName += nowDate;
            // 设置输出的格式
            response.setCharacterEncoding("UTF-8");
            response.addHeader("content-type", "application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            //关闭流
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
